<template>
  <HeaderNavTabarVue :title="title" />
	<view class="uv-empty" v-if="constructionList.length === 0">
		<uv-empty :text="emptyText" icon="../../../static/images/empty.png"></uv-empty>
	</view>
  <view class="constructionList" v-else :style="'min-height: ' + boxHeight + 'rpx;'">
    <SiftCom
      @searchEmit="searchEmit"
			@siftList="siftList"
      @resetEmit="resetEmit"
      @popupSiftOpen="popupSiftOpen"
      :show="true"
    >
      <view class="picker-content">
        <view class="measurement-info-list">
          <text class="info-list-left">接单日期</text>
          <view class="info-list-right" @tap="openPicker">
            <view class="info-content">
              {{ searcData.takeOrdersDate }}
            </view>
            <i class="iconfont icon-youjiantou"></i>
          </view>
        </view>
      </view>
      <view class="picker-content">
        <view class="measurement-info-list">
          <text class="info-list-left">施工队编号</text>
          <view class="info-list-right">
            <view class="info-content">
              <input adjust-position class="uni-input" v-model="searcData.constructionTeamId" />
            </view>
          </view>
        </view>
      </view>
      <view class="picker-content">
        <view class="measurement-info-list">
          <text class="info-list-left">施工队名称</text>
          <view class="info-list-right">
            <view class="info-content">
              <input adjust-position class="uni-input" v-model="searcData.constructionTeamName" />
            </view>
          </view>
        </view>
      </view>
    </SiftCom>
    <main class="box-main">
      <CardList
        v-for="(item, index) in constructionList"
        :key="index"
        :manufacturerContact="item.customerName"
        :customerId="item.orderId"
        :designType="item.creator"
        :detailedAddress="item.customerStore"
        :terminalName="item.customerStore"
        mainFloorSvg="安装过程"
        :terminalPhone="item.completionIsRequiredDate"
        :surveyDate="item.dispatchDate"
        @tap="goDetail(item.id,item.process.status)"
      >
        <view class="btn-install-order-list">
          <uni-steps :options="list1" :active="isActive(item.process.status)" />

          <view class="btn-flex" v-if="item.process.status === '未接单'">
            <button class="拒接" @tap.stop="rejectionFn(item)">拒接</button>
            <button class="接单" @tap.stop="insertProcessFn(item)">接单</button>
          </view>
          <button class="施工中 row-btn" v-if="item.process.status === '施工中'" @tap.stop="goUploadView(item.id,'施工中')">上传图片</button>
          <button class="上传工费 row-btn" v-if="item.process.status === '上传工费'" @tap.stop="goUploadView(item.id,'上传工费')">上传工费单</button>
          <button class="待分配 row-btn" v-if="item.process.status === '待分配'">已拒接</button>
          <button class="已完成 row-btn" v-if="item.process.status === '已完成'">已完成</button>
          <button class="已超时 row-btn" v-if="item.process.status === '已超时'">已超时{{ item.timeoutPeriod }}天</button>
        </view>
      </CardList>
    </main>
    <view class="animbox-scroll-loading" v-show="statusLoding">
      <view></view>
      <view></view>
      <view></view>
      <view></view>
      <view></view>
    </view>
  </view>
  <uv-datetime-picker
    ref="datetimePicker"
    :modal-append-to-body="false"
    v-model="pickerValue"
    mode="date"
    :formatter="formatter"
    round="32 32 0 0"
    @confirm="confirm"
  >
  </uv-datetime-picker>
</template>

<script setup>
import HeaderNavTabarVue from '@/components/HeaderNavTabar/HeaderNavTabar.vue'
import SiftCom from '@/components/siftCom/siftCom.vue'
import CardList from '@/components/cardList/cardList.vue'
import MyPicker from '@/components/MyPicker/MyPicker.vue'
import { getNowDate } from '@/utils/date.js'
import {
  getWorkApi,
  constructionOrdersListApi,
  acceptRejectionApi
} from '@/api/customer.js'
import { onLoad, onReachBottom,onShow } from '@dcloudio/uni-app'
import { ref, reactive ,toRefs} from 'vue'
import { getTitleBarHeight } from '@/utils/system.js'
import { getUserProfile } from '@/api/system/user.js'
import store from '@/store'

const title = '安装队订单列表'
const boxHeight = (uni.getSystemInfoSync().windowHeight - getTitleBarHeight()) * 2

let phone = ref(null)

// 搜索的数据
let searcData = ref({
  surveyDate: '',
  constructionTeamName: '',
  takeOrdersDate: '',
  customerId: '',
  customerName: '',
  type: '',
  constructionTeamId: '',
	sortType:'',//1升序 2降序
})
const emptyText = ref('数据请求中...')
let constructionList = ref([])
// 筛选日期
// 刷选日期
let pickerValue = ref(Number(new Date()))
const datetimePicker = ref(null)

const openPicker = () => {
  datetimePicker.value.open()
}
const formatter = (type, value) => {
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  return value
}
const confirm = (e) => {
  pickerValue.value = getNowDate(e.value)
  searcData.value.takeOrdersDate = getNowDate(e.value)
}
const customerPickerRef = ref(null) // 这个时候获取了子组件 Comp
// 客户信息
let customerList = ref([])
// 获取客户下拉菜单数据
const getWorkApiData = async (v = '') => {
  let params = {
    customerName: v
  }
  let { code, data } = await getWorkApi(params)
  if (code == 200) {
    data.forEach((v) => {
      // customerList.value.push({
      //   label: v.primaryClassification + '/' + v.customerName,
      //   value: v.customerId
      // })
			// 过滤掉 null
			customerList.value.push({
			  label:  [v.primaryClassification,v.customerName].filter(item => item != null).join('/'),
			  value: v.customerId,
			})
    })
    store.commit('setCustomerList', customerList.value)
  }
}

// 选择的客户数据
const getVlaue = (v) => {
  searcData.value.customerId = v.value
  searcData.value.customerName = v.label
  customerPickerRef.value.closePop()
}
// 打开模态床
const toggle = () => {
  customerPickerRef.value.toggle('bottom') // 调用子组件的 show 方法
}

// 打开筛选狂
const popupSiftOpen = () => {
  for (let key in searcData.value) {
    if (searcData.value[key]) {
      searcData.value[key] = ''
    }
  }
}


const stepsList = reactive({
  active: 1,
  list1: [
    {
      title: '未接单',
    },
    {
      title: '施工中',
    },
    {
      title: '上传工费',
    },
    {
      title: '待验收',
    },
    {
      title: '已完成',
    },
  ],
})
let { active, list1 } = toRefs(stepsList)
const isActive = (status) => {
  if(status === '未接单'){
   return  active.value = 0
  }else if(status === '施工中'){
   return active.value = 1
  }else if(status === '上传工费'){
   return active.value =  2
  }else if(status === '待验收' || status === '待回访'){
   return active.value = 3
  }else if(status === '已完成'){
   return active.value = 4
  }
}

const goUploadView = (id,status)=>{
  uni.navigateTo({
    url: '/pages/install/installUpload/installUpload?id=' + id+'&status='+status,
  })
}

const goDetail = (id,status)=>{
  uni.navigateTo({
    url: '/pages/install/installDetail/installDetail?id=' + id+'&status='+status,
  })
}

const resetEmit = (v) => {
  constructionListFn()
  v.close()
}

const siftList = (v) => {
	// console.log(v,'vvv') // 0 降序 1 升序
	pageNum.value = 1
	searcData.value.sortType = Number(v) + 1
	constructionListFn(searcData.value, false)
}

const searchEmit = (v) => {
  pageNum.value = 1
  constructionListFn(searcData.value, false)
  v.close()
}

let pageNum = ref(1)
let pageSize = ref(30)
let totals = ref(888)
let statusLoding = ref(false)
const constructionListFn = async (data = {}, flag = true) => {
  let page = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    phone: (await getUserProfile()).data.phonenumber
  }
  let params = Object.assign(data, page)
  let res = await constructionOrdersListApi(params)
  let { code, rows, total } = res
  try {
    if (code === 200) {
      if (statusLoding.value) {
        statusLoding.value = false //加载中状态
      }
      if (flag) {
        constructionList.value = [...constructionList.value, ...rows]
      } else {
        constructionList.value = rows
      }
      totals.value = total
			
			if(constructionList.value.length === 0){
				emptyText.value = '列表为空'
			}
    }
  } catch {
  }
}
onReachBottom(() => {
  statusLoding.value = true //加载完状态
  let allTotal = pageNum.value * pageSize.value
  if (allTotal < totals.value) {
    pageNum.value++
    constructionListFn()
  } else {
    uni.showToast({
      title: '数据加载完毕'
    })
    statusLoding.value = false
  }
})



const insertProcessFn = (v) => {
  let params = {
    id: v.id,
    type: '同意'
  }
  uni.showModal({
    content: '您确认要接下此单吗？', //
    success: (res) => {
      if (res.confirm) {
        acceptRejectionApi(params).then((apiData) => {
          if (apiData.code === 200) {
            constructionListFn({},false)
            uni.showToast({
              icon: 'success',
              title: '同意成功'
            })
          }
        })

      }
    }
  })
}
const rejectionFn = async (v) => {
  let params = {
    id: v.id,
    type: '拒绝'
  }
  uni.showModal({
    content: '您确认要拒接此单吗？', //模板中提示的内容
    success: async (res) => {
      if (res.confirm) {
        acceptRejectionApi(params).then((apiData) => {
          if (apiData.code === 200) {
            constructionListFn({},false)
            uni.showToast({
              icon: 'success',
              title: '拒接成功'
            })
          }
        })
      }
    }
  })
}

onShow(async () => {
  await constructionListFn({},false)
})
onLoad(async ()=>{
  await getWorkApiData()
})
</script>

<style lang="scss" scoped>
@import '@/static/style/index.scss';

:deep(.uni-input-input) {
  text-align: right;
}

.constructionList {
  padding: 0 32rpx 24rpx 32rpx;
  box-sizing: border-box;
  background-color: $uni-bai;

  .box-main {
    padding: 107rpx 0;
    box-sizing: border-box;

    .btn-install-order-list {
      margin-top: 20rpx;

      button {
        height: 56rpx;
        @include flex($justify: center, $align: center);
        border: none;
      }

      .btn-flex {
        @include flex($justify: space-between, $align: center);

        .接单 {
          background-color: #165dff;
          color: #fff;
        }
        .拒接 {
          background-color: #ffece8;
          color: #f53f3f;
        }

        button {
          width: 291rpx;
        }
      }

      .进行中,.上传工费 {
        background-color: #e8f3ff;
        color: #165dff;
      }
      .施工中 {
        background-color: #e8f3ff;
        color: #165dff;
      }

      .已拒接,
      .已超时 {
        background-color: #ffece8;
        color: #f53f3f;
      }

      .已完成 {
        background-color: #e8ffea;
        color: #00b42a;
      }

      .待验收 {
        background-color: #fff7e8;
        color: #ff7d00;
      }

      .row-btn {
        width: 100%;
      }
    }
  }
}

.measurement-info-list {
  @include flex($align: center, $justify: space-between);
  padding: $spacing-row-base;

  .info-list-left {
    // @include font-color-auxiliary;
    color: $uni-fc-fu-lin;
    font-size: $font-size-base;
  }

  .info-list-right {
    @include flex($align: center);

    .info-content {
      @include textStyleBase;
      font-size: 34rpx;
    }

    .iconfont {
      margin-left: 16rpx;
      // @include font-color-auxiliary;
      color: $uni-fc-fu-lin;
    }
  }

  .unit {
    // @include font-color-auxiliary;
    color: $uni-fc-fu-lin;
  }
}
</style>
